package com.yangqun.util;

import com.yangqun.annotation.ExcelBeanMethodUtil;

import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.List;

public class ReflexUtil<T> {

    /**
     * YangTao  2017年5月3日 15:10:09
     * @Title: getMethodName
     * @Description: (通过反射获取实体Excel表头和方法对应)
     * @param @param excelExportMustImpMethodBean
     * @param @param headName
     * @param @return
     * @return String
     */
    public String getMethodName(Field[] fields, String headName){
        for(Field f : fields){
            ExcelBeanMethodUtil excelBeanMethodUtil = f.getAnnotation(ExcelBeanMethodUtil.class);
            if(excelBeanMethodUtil == null){
                continue;
            }
            if(excelBeanMethodUtil.excelHeadName().equals(headName)){
                return excelBeanMethodUtil.writeInvokeMethod();
            }else{
                continue;
            }
        }
        return null;
    }
    /**
     * YangTao 2017年5月3日 15:25:56
     * @Title: getExcelHeadByBean
     * @Description: (根据反射获取bean上的ExcelheadName用于生产Excel的head)
     * @param @param excelExportMustImpMethodBean
     * @return String[]
     * @throws Exception
     */
    public String[] getExcelHeadByBean(T excelExportMustImpMethodBean){

        Field[] fields = excelExportMustImpMethodBean.getClass().getFields();

        List<String> list = new ArrayList<String>();
        for(Field f : fields){
            ExcelBeanMethodUtil excelBeanMethodUtil = f.getAnnotation(ExcelBeanMethodUtil.class);
            if(excelBeanMethodUtil == null){
                continue;
            }
            list.add(excelBeanMethodUtil.excelHeadName());
        }
        return (String[])list.toArray(new String[list.size()]);
    }
    /**
     * YangTao 2017年4月20日 11:23:10
     * @Title: getMethodByName
     * @Description: (根据名字获取方法)
     * @param @param ms
     * @param @param methodName
     * @param @return
     * @return Method
     */
    public Method getMethodByName(Method[] ms, String methodName){
        for(int i = 0; i < ms.length; i++){
            if(methodName.equals(ms[i].getName())){
                return ms[i];
            }else{
                continue;
            }
        }
        return null;
    }

    public static String getAttributeName(Field[] fields, String headName){
        for(Field f : fields){
            ExcelBeanMethodUtil excelBeanMethodUtil = f.getAnnotation(ExcelBeanMethodUtil.class);
            if(excelBeanMethodUtil == null){
                continue;
            }
            if(excelBeanMethodUtil.excelHeadName().equals(headName)){
                return excelBeanMethodUtil.attributeName();
            }else{
                continue;
            }
        }
        return null;
    }

}
